package com.rivues.module.manage.web.handler.task;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.mgt.SimpleSession;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.rivu.handler.DCriteriaPageSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.handler.RequestData;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.model.ClusterServer;
import com.rivues.module.platform.web.model.ConfigureParam;
import com.rivues.module.platform.web.model.HistoryJobDetail;
import com.rivues.module.platform.web.model.JobDetail;
import com.rivues.module.platform.web.model.RivuSite;
import com.rivues.module.platform.web.model.SearchSetting;
import com.rivues.module.platform.web.model.User;
import com.rivues.util.RivuTools;
import com.rivues.util.local.LocalTools;
import com.rivues.util.tools.TaskHelper;
  
@Controller  
@RequestMapping("/{orgi}/manage/task")  
public class TaskController extends Handler{  
	private final Logger log = LoggerFactory.getLogger(TaskController.class); 
	

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/taskpassing" , name="taskpassing" , type="manage",subtype="task")
    public ModelAndView taskpassing(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/task/taskpassing") , orgi) ;
    	
    	List<JobDetail> historytasks = null;
    	DetachedCriteria criteria = DetachedCriteria.forClass(JobDetail.class).add(Restrictions.ne("taskstatus","0")).addOrder(Order.asc("nextfiretime"));
    	
    	String plantask = request.getParameter("plantask");
    	if(plantask!=null&&!"".equals(plantask)){
    		criteria.add(Restrictions.eq("plantask",Boolean.valueOf(plantask)));
    	}
    	modelView.addObject("plantask",plantask);
    	String timeType = request.getParameter("timeType");
    	if(timeType==null)timeType="1";
    	modelView.addObject("timeType",timeType);
    	if("1".equals(timeType)){
    		String times = request.getParameter("times");
    		if(times==null)times="4";
    		criteria.add(Restrictions.le("taskfiretime",new Date()))
    		.add(Restrictions.gt("taskfiretime",new Date(System.currentTimeMillis()-3600*Long.valueOf(times)*1000)));
    		modelView.addObject("times",times);
    	}else{
    		String beginTime = request.getParameter("beginTime");
    		String endTime = request.getParameter("endTime");
    		if(beginTime!=null&&!"".equals(beginTime)){
    			criteria.add(Restrictions.gt("taskfiretime",RivuTools.stringToDate(beginTime)));
    		}
    		if(endTime!=null&&!"".equals(endTime)){
    			criteria.add(Restrictions.le("taskfiretime",RivuTools.stringToDate(endTime)));
    		}
    		modelView.addObject("beginTime",beginTime);
    		modelView.addObject("endTime",endTime);
    		
    	}
    	//用户检索
    	 
    	String userid = request.getParameter("userid");
    	if(userid!=null&&!"".equals(userid)){
    		criteria.add(Restrictions.eq("userid",userid));
    		String username = request.getParameter("username");
    		if(username==null){
    			List<User> users = RivuDataContext.getOnlineUser();
        		User user = null;
        		for (int i = 0; i < users.size(); i++) {
    				user = users.get(i);
    				if(userid.equals(user.getId())){
    					username = user.getUsername();
    				}
    			}
        		modelView.addObject("uid",userid);
    		}
        	modelView.addObject("username",username);
    	}
    	modelView.addObject("userid",userid);
    	
    	
    	//报表检索
    	String reportid = request.getParameter("reportid");
    	if(reportid!=null&&!"".equals(reportid)){
    		criteria.add(Restrictions.like("dataid",reportid, MatchMode.ANYWHERE));
    	}
    	modelView.addObject("reportid",reportid);
    	String reportname = request.getParameter("reportname");
    	modelView.addObject("reportname",reportname);
    	
    	//报表目录检索
    	String dicid = request.getParameter("dicid");
    	if(dicid!=null&&!"".equals(dicid)){
    		criteria.add(Restrictions.like("dicid",dicid, MatchMode.ANYWHERE));
    	}
    	modelView.addObject("dicid",dicid);
    	String dicname = request.getParameter("dicname");
    	modelView.addObject("dicname",dicname);
    	
    	String priority = request.getParameter("priority");
    	if(priority!=null&&!"".equals(priority)){
    		criteria.add(Restrictions.eq("priority",Integer.valueOf(priority)));
    	}
    	modelView.addObject("priority",priority);
    	String status = request.getParameter("status");
    	if(status!=null&&!"".equals(status)){
    		if("1".equals(status)){//正在执行
    			criteria.add(Restrictions.eq("fetcher",true));
    		}else if("2".equals(status)){//等待中		
    			criteria.add(Restrictions.eq("taskstatus","1"));
    		}else{//已挂起
    			criteria.add(Restrictions.eq("pause",true));
    		}
    		
    	}
    	modelView.addObject("status",status);
    	DetachedCriteria tempCriteria =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(criteria));
    	
    	modelView = super.page(request, orgi, modelView, criteria, "beginNum", "endNum", "historytasks");
    	DetachedCriteria c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	//正在执行
    	modelView.addObject("excutingcount",super.getService().getCountByCriteria(c.add(Restrictions.eq("taskstatus","2"))));
    	//正在等待数量
    	c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("waitingcount",super.getService().getCountByCriteria(c.add(Restrictions.eq("taskstatus","1"))));
    	//已挂起数量
    	c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("stopcount",super.getService().getCountByCriteria(c.add(Restrictions.eq("pause",true))));
    	//全部数量
    	c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("allcount",super.getService().getCountByCriteria(c));
    	return modelView;
    }


    @SuppressWarnings("unchecked")
    @RequestMapping(value="/taskpassed" , name="taskpassed" , type="manage",subtype="task")
    public ModelAndView taskpassed(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/task/taskpassed") , orgi) ;
    	List<HistoryJobDetail> historytasks = null;
    	
    	DetachedCriteria criteria = DetachedCriteria.forClass(HistoryJobDetail.class).add(Restrictions.eq("orgi",orgi)).addOrder(Order.desc("starttime"));
    	String timeType = request.getParameter("timeType");
    	if(timeType==null)timeType="1";
    	modelView.addObject("timeType",timeType);
    	if("1".equals(timeType)){
    		String times = request.getParameter("times");
    		if(times==null)times="4";
    		criteria.add(Restrictions.le("starttime",new Date()))
    		.add(Restrictions.gt("starttime",new Date(System.currentTimeMillis()-3600*Long.valueOf(times)*1000)));
    		modelView.addObject("times",times);
    	}else{
    		String beginTime = request.getParameter("beginTime");
    		String endTime = request.getParameter("endTime");
    		if(beginTime!=null&&!"".equals(beginTime)){
    			criteria.add(Restrictions.gt("starttime",RivuTools.stringToDate(beginTime)));
    		}
    		if(endTime!=null&&!"".equals(endTime)){
    			criteria.add(Restrictions.le("starttime",RivuTools.stringToDate(endTime)));
    		}
    		modelView.addObject("beginTime",beginTime);
    		modelView.addObject("endTime",endTime);
    		
    	}
    	//用户检索
    	String userid = request.getParameter("userid");
    	if(userid!=null&&!"".equals(userid)){
    		criteria.add(Restrictions.eq("userid",userid));
    		String username = request.getParameter("username");
    		if(username==null){
    			List<User> users = RivuDataContext.getOnlineUser();
        		User user = null;
        		for (int i = 0; i < users.size(); i++) {
    				user = users.get(i);
    				if(userid.equals(user.getId())){
    					username = user.getUsername();
    				}
    			}
        		modelView.addObject("uid",userid);
    		}
        	modelView.addObject("username",username);
    	}
    	modelView.addObject("userid",userid);
    	
    	//报表检索
    	String reportid = request.getParameter("reportid");
    	if(reportid!=null&&!"".equals(reportid)){
    		criteria.add(Restrictions.like("dataid",reportid, MatchMode.ANYWHERE));
    	}
    	modelView.addObject("reportid",reportid);
    	String reportname = request.getParameter("reportname");
    	modelView.addObject("reportname",reportname);
    	
    	//报表目录检索
    	String dicid = request.getParameter("dicid");
    	if(dicid!=null&&!"".equals(dicid)){
    		criteria.add(Restrictions.like("dicid",dicid, MatchMode.ANYWHERE));
    	}
    	modelView.addObject("dicid",dicid);
    	String dicname = request.getParameter("dicname");
    	modelView.addObject("dicname",dicname);
    	
    	String priority = request.getParameter("priority");
    	if(priority!=null&&!"".equals(priority)){
    		criteria.add(Restrictions.eq("priority",Integer.parseInt(priority)));
    	}
    	modelView.addObject("priority",priority);
    	String resulttype = request.getParameter("resulttype");
    	if(resulttype!=null&&!"".equals(resulttype)){
    		criteria.add(Restrictions.eq("resulttype",Integer.parseInt(resulttype)));
    	}
    	modelView.addObject("resulttype",resulttype);
    	
    	DetachedCriteria tempCriteria =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(criteria));
    	
    	modelView = super.page(request, orgi, modelView, criteria, "beginNum", "endNum", "historytasks");
    	
    	
    	//成功的数量
    	DetachedCriteria c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("successcount",super.getService().getCountByCriteria(c.add(Restrictions.eq("resulttype",1))));
    	//失败的数量
    	c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("faildcount",super.getService().getCountByCriteria(c.add(Restrictions.eq("resulttype",2))));
    	//取消的数量
    	c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("cancelcount",super.getService().getCountByCriteria(c.add(Restrictions.eq("resulttype",3))));
    	//总的数量
    	c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("allcount",super.getService().getCountByCriteria(c));
    	return modelView;
    }
    

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/taskwillpass" , name="taskwillpass" , type="manage",subtype="task")
    public ModelAndView taskwillpass(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/task/taskwillpass") , orgi) ;
    	List<JobDetail> historytasks = null;
    	
    	DetachedCriteria criteria = DetachedCriteria.forClass(JobDetail.class).add(Restrictions.eq("taskstatus","0")).add(Restrictions.eq("orgi",orgi)).addOrder(Order.asc("nextfiretime"));
    	
    	String timeType = request.getParameter("timeType");
    	if(timeType==null)timeType="1";
    	modelView.addObject("timeType",timeType);
    	if("1".equals(timeType)){
    		String times = request.getParameter("times");
    		if(times==null)times="4";
    		criteria.add(Restrictions.ge("nextfiretime",new Date()));
    		if(!"all".equals(times)){
    			criteria.add(Restrictions.le("nextfiretime",new Date(System.currentTimeMillis()+Long.valueOf(times) * 3600 * 1000)));
    		}	
    		modelView.addObject("times",times);
    	}else{
    		String beginTime = request.getParameter("beginTime");
    		String endTime = request.getParameter("endTime");
    		if(beginTime!=null&&!"".equals(beginTime)){
    			criteria.add(Restrictions.gt("nextfiretime",RivuTools.stringToDate(beginTime)));
    		}
    		if(endTime!=null&&!"".equals(endTime)){
    			criteria.add(Restrictions.le("nextfiretime",RivuTools.stringToDate(endTime)));
    		}
    		modelView.addObject("beginTime",beginTime);
    		modelView.addObject("endTime",endTime);
    		
    	}
    	
    	//用户检索
    	String userid = request.getParameter("userid");
    	if(userid!=null&&!"".equals(userid)){
    		criteria.add(Restrictions.eq("userid",userid));
    		String username = request.getParameter("username");
    		if(username==null){
    			List<User> users = RivuDataContext.getOnlineUser();
        		User user = null;
        		for (int i = 0; i < users.size(); i++) {
    				user = users.get(i);
    				if(userid.equals(user.getId())){
    					username = user.getUsername();
    				}
    			}
        		modelView.addObject("uid",userid);
    		}
        	modelView.addObject("username",username);
    	}
    	modelView.addObject("userid",userid);
    	
    	//报表检索
    	String reportid = request.getParameter("reportid");
    	if(reportid!=null&&!"".equals(reportid)){
    		criteria.add(Restrictions.like("dataid",reportid, MatchMode.ANYWHERE));
    	}
    	modelView.addObject("reportid",reportid);
    	String reportname = request.getParameter("reportname");
    	modelView.addObject("reportname",reportname);
    	
    	//报表目录检索
    	String dicid = request.getParameter("dicid");
    	if(dicid!=null&&!"".equals(dicid)){
    		criteria.add(Restrictions.like("dicid",dicid, MatchMode.ANYWHERE));
    	}
    	modelView.addObject("dicid",dicid);
    	String dicname = request.getParameter("dicname");
    	modelView.addObject("dicname",dicname);
    	
    	String priority = request.getParameter("priority");
    	if(priority!=null&&!"".equals(priority)){
    		criteria.add(Restrictions.eq("priority",Integer.valueOf(priority)));
    	}
    	modelView.addObject("priority",priority);
    	String status = request.getParameter("status");
    	if(status!=null&&!"".equals(status)){
    		if("1".equals(status)){//已计划
    			criteria.add(Restrictions.eq("fetcher",true));
    		}else{//已取消
    			criteria.add(Restrictions.eq("fetcher",false));
    		}
    	}
    	modelView.addObject("status",status);
    	DetachedCriteria tempCriteria =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(criteria));
    	
    	modelView = super.page(request, orgi, modelView, criteria, "beginNum", "endNum", "historytasks");
    	//已计划
    	DetachedCriteria c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("plancount",super.getService().getCountByCriteria(c.add(Restrictions.eq("fetcher",true))));
    	//已取消
    	c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("cancelcount",super.getService().getCountByCriteria(c.add(Restrictions.eq("fetcher",false))));
    	//全部
    	c =(DetachedCriteria)RivuTools.toObject(RivuTools.toBytes(tempCriteria));
    	modelView.addObject("allcount",super.getService().getCountByCriteria(c.add(Restrictions.eq("taskstatus","0"))));
    	return modelView;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/{taskid}/taskruninglist" , name="taskruninglist" , type="manage",subtype="task")
    public ModelAndView taskruninglist(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String taskid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/manage/task/taskruninglist") , orgi) ;
    	List<HistoryJobDetail> historytasks = null;
    	List<HistoryJobDetail> hisJobList = super.getService().findPageByCriteria(DetachedCriteria.forClass(HistoryJobDetail.class).add(Restrictions.eq("id",taskid))) ;
    	Object task = hisJobList.size()>0 ? hisJobList.get(0) : null ;
    	String jobId = "";
    	if(task == null){
    		List<JobDetail> jobList = super.getService().findPageByCriteria(DetachedCriteria.forClass(JobDetail.class).add(Restrictions.eq("id",taskid))) ;
    		if(jobList.size()>0){
    			task = jobList.get(0) ;
    			jobId = ((JobDetail)task).getId();
    			if(task!=null && "2".equals(((JobDetail)task).getTaskstatus())){
    				Object report = RivuDataContext.getClusterInstance().get(RivuDataContext.DistributeEventEnum.RUNNINGJOBREPORT.toString()).get(taskid);
    				if(report!=null){
    					modelView.addObject("report", report) ;
    				}
    			}
    		}
    	}else{
    		jobId = ((HistoryJobDetail)task).getTaskid() ;
    	}
    	DetachedCriteria criteria = DetachedCriteria.forClass(HistoryJobDetail.class).add(Restrictions.eq("orgi",orgi)).add(Restrictions.eq("taskid",jobId)).addOrder(Order.desc("starttime"));
    	String status = request.getParameter("status");
    	if(status!=null&&!"".equals(status)&&!"0".equals(status)){
    		criteria.add(Restrictions.eq("resulttype",Integer.parseInt(status)));
    	}else{
    		status = "0";
    	}
    	modelView.addObject("status",status);
    	
    	modelView = super.page(request, orgi, modelView, criteria, "beginNum", "endNum", "historytasks");
    	modelView.addObject("task",task);
    	return modelView;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/{taskid}/taskdetail" , name="taskdetail" , type="manage",subtype="task")
    public ModelAndView taskdetail(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String taskid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/manage/task/taskdetail") , orgi) ;
    	HistoryJobDetail task = (HistoryJobDetail)super.getService().getIObjectByPK(HistoryJobDetail.class, taskid);
    	String statusmsg = task.getStatus();
    	List<Map<String, String>> list = new ArrayList<Map<String,String>>();
    	if(statusmsg!=null){
    		String statuspers[] = statusmsg.split(";");
        	
        	Map<String, String> map = null;
        	String statusper = null;
        	String[] pers = null;
        	for (int i = 0; i < statuspers.length; i++) {
        		statusper = statuspers[i];
        		pers = statusper.split(":");
        		map = new HashMap<String, String>();
        		Map<String , Object> values = new HashMap<String , Object>();
        		values.put("job", task) ;
    			map.put("msg", LocalTools.getMessage(pers[0] , values));
    			map.put("time", RivuTools.dateToString(new Date(Long.valueOf(pers[1])), "yyyy-MM-dd HH:mm:ss"));
    			list.add(map);
    		}
    	}
    	
    	modelView.addObject("task",task);
    	modelView.addObject("statusmsgs",list);
    	return modelView;
    }

	@SuppressWarnings("unchecked")
    @RequestMapping(value="/{taskid}/taskreexcute" , name="taskreexcute" , type="manage",subtype="task")
    public ModelAndView taskreexcute(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String taskid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/public/success") , orgi) ;
    	List<JobDetail> list = super.getService().findPageByCriteria(DetachedCriteria.forClass(JobDetail.class).add(Restrictions.eq("id",taskid)),1,1);
    	if(list.size()>0){
    		JobDetail job = list.get(0);
    		job.setTaskstatus("1");
    		super.getService().updateIObject(job);
    		modelView.addObject("data",LocalTools.getMessage("S_TASK_1000010001"));
    	}else{
    		modelView.addObject("data",LocalTools.getMessage("E_TASK_1000010001"));
    	}
    	return modelView;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/{taskid}/taskpriorityedit" , name="taskpriorityedit" , type="manage",subtype="task")
    public ModelAndView taskpriorityedit(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String taskid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/manage/task/taskpriority") , orgi) ;
    	modelView.addObject("task",super.getService().getIObjectByPK(JobDetail.class, taskid));
    	return modelView;
    }
    
    @SuppressWarnings("unchecked")
    @RequestMapping(value="/{taskid}/taskpriorityedito" , name="taskpriorityedito" , type="manage",subtype="task")
    public ModelAndView taskpriorityedito(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String taskid,@Valid String priorityset) throws Exception{ 
    	
    	JobDetail task = (JobDetail)super.getService().getIObjectByPK(JobDetail.class, taskid);
    	task.setPriority(Integer.valueOf(priorityset));
    	super.getService().updateIObject(task);
    	String alluser = request.getParameter("alluser");
    	if(alluser!=null&&!"".equals(alluser)){
    		List<JobDetail> list = super.getService().findAllByCriteria(DetachedCriteria.forClass(JobDetail.class).add(Restrictions.eq("userid",task.getUserid())));
    		JobDetail job = null;
    		for (int i = 0; i < list.size(); i++) {
				job = list.get(i);
				job.setPriority(Integer.valueOf(priorityset));
				super.getService().updateIObject(job);
			}
    	}
    	ModelAndView modelView = this.taskwillpass(request, orgi, data);
    	modelView.addObject("ation_message",LocalTools.getMessage("S_TASK_1000010002"));
    	return modelView;
    }
    
    @RequestMapping(value="/{taskid}/taskcancel" , name="taskcancel" , type="manage",subtype="task")
    public ModelAndView taskcancel(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String taskid) throws Exception{
    	String stoptype = request.getParameter("stoptype");
    	ModelAndView modelView = null;
    	List<JobDetail> jobs = super.getService().findAllByCriteria(DetachedCriteria.forClass(JobDetail.class).add(Restrictions.eq("id",taskid)));
    	if(jobs.size()>0){
    		if(stoptype==null||"".equals(stoptype)){
        		JobDetail job = (JobDetail)super.getService().getIObjectByPK(JobDetail.class, taskid);
        		
        		job.setFetcher(false);
        		super.getService().updateIObject(job);
        		modelView = this.taskwillpass(request, orgi, data) ;
        		modelView.addObject("ation_message",LocalTools.getMessage("S_TASK_1000010003"));
        	}else{
        		JobDetail job = (JobDetail)super.getService().getIObjectByPK(JobDetail.class, taskid);
        		job.setFetcher(false);
        		super.getService().updateIObject(job);
        		TaskHelper.stopTaskJob(taskid , TaskHelper.TaskStopType.STOP_AFTER_ALL_REQUEST.toString()) ;
        		modelView = this.taskpassing(request, orgi, data);
        	}
    	}else{
    		modelView = this.taskwillpass(request, orgi, data) ;
    	}
    	
    	
    	return modelView;
    }
    
    @RequestMapping(value="/{taskid}/taskstart" , name="taskstart" , type="manage",subtype="task")
    public ModelAndView taskstart(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String taskid) throws Exception{ 
    	JobDetail job = (JobDetail)super.getService().getIObjectByPK(JobDetail.class, taskid);
		job.setFetcher(true);
		super.getService().updateIObject(job);
		ModelAndView modelView = this.taskwillpass(request, orgi, data) ;
		modelView.addObject("ation_message",LocalTools.getMessage("S_TASK_1000010004"));
    	return modelView;
    }
    
    @RequestMapping(value="/{taskid}/taskstop" , name="taskstop" , type="manage",subtype="task")
    public ModelAndView taskstop(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String taskid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/public/success") , orgi) ;
    	TaskHelper.stopTaskJob(taskid, TaskHelper.TaskStopType.STOP_PAUSE.toString());
    	JobDetail job = (JobDetail)super.getService().getIObjectByPK(JobDetail.class, taskid);
		job.setPause(true) ;
		super.getService().updateIObject(job);
    	return this.taskpassing(request, orgi, data);
    }
    
    @RequestMapping(value="/{taskid}/taskrestart" , name="taskrestart" , type="manage",subtype="task")
    public ModelAndView taskrestart(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data,@PathVariable String taskid) throws Exception{ 
    	ModelAndView modelView = request(new ResponseData("/pages/public/success") , orgi) ;
    	TaskHelper.stopTaskJob(taskid, TaskHelper.TaskStopType.RESTART.toString());
    	JobDetail job = (JobDetail)super.getService().getIObjectByPK(JobDetail.class, taskid);
		job.setPause(false) ;
		super.getService().updateIObject(job);
    	return this.taskpassing(request, orgi, data);
    }
    

    /**
     * 在线用户列表查询
     * @param request
     * @param orgi
     * @param data
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value="/onlineuser" , name="onlineuser" , type="manage",subtype="task")
    public ModelAndView onlineuser(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/task/onlineuser") , orgi) ;

    	//强制踢出用户
		if (StringUtils.isNotBlank(request.getParameter("sessionId"))) {
			String sessionid = request.getParameter("sessionId").toString();
	    	Collection<?> collections = RivuDataContext.getSessionDao().getActiveSessions();
			Iterator iterator = collections.iterator() ;
	    	while (iterator.hasNext()) {
				SimpleSession session = (SimpleSession)iterator.next();
				if (session.getId().equals(sessionid)) {
					RivuDataContext.getSessionDao().delete(session);
					break;
				}
	    	}
		}
    	
    	
    	Collection<?> collection = RivuDataContext.getSessionDao().getActiveSessions();
		List list = new ArrayList();
    	if (collection!=null && collection.size()>0) {
    		
    		

    		int recs = 0 ;
    		//页码data.getP()
    		//每页条数data.getPs()
			int dataBegin = data.getP() * data.getPs();//当前页起始条数
    		
    		//过滤器结果List
    		List compareList = new ArrayList();
    		Iterator iterator = collection.iterator() ;
    		Date rangeDate = null;//时间范围
    		Date startDate = null;//开始时间
    		Date endDate = null;//结束时间
    		String userName = "";//登陆用户
    		String status = "";//状态
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar nowTime = Calendar.getInstance();
			if(request.getParameter("thischecked")!=null){
				String thischecked = request.getParameter("thischecked").toString();
				if (StringUtils.isNotBlank(thischecked)) {
					modelView.addObject("thischecked", thischecked);
				}
			}
    		if (request.getParameter("rangeTime")!=null) {
    			String rangeTime = request.getParameter("rangeTime").toString();
    			if (StringUtils.isNotBlank(rangeTime)) {
    				if (rangeTime.equals("0")) {
    					nowTime.add(Calendar.MINUTE, -5);
					}
    				if (rangeTime.equals("1")) {
    					nowTime.add(Calendar.MINUTE, -30);
					}
    				if (rangeTime.equals("2")) {
    					nowTime.add(Calendar.HOUR, -1);
					}
    				if (rangeTime.equals("3")) {
    					nowTime.add(Calendar.HOUR, -4);
					}
    				if (rangeTime.equals("4")) {
    					nowTime.add(Calendar.HOUR, -12);
					}
    				if (rangeTime.equals("5") || rangeTime.equals("6")) {
    					nowTime.add(Calendar.HOUR, -24);
					}
        			modelView.addObject("rangeTime", rangeTime);
    				rangeDate = nowTime.getTime();
				}
			}else{
				nowTime.add(Calendar.MINUTE, -30);
				rangeDate = nowTime.getTime();
				
			}
    		if (request.getParameter("startTime")!=null) {
    			String startTime = request.getParameter("startTime").toString();
    			modelView.addObject("startTime", startTime);
    			if (StringUtils.isNotBlank(startTime)) {
        			startDate = sdf.parse(startTime);
				}
			}
    		if (request.getParameter("endTime")!=null) {
    			String endTime = request.getParameter("endTime").toString();
    			modelView.addObject("endTime", endTime);
    			if (StringUtils.isNotBlank(endTime)) {
        			endDate = sdf.parse(endTime);
    			}
			}
    		if (request.getParameter("userName")!=null) {
    			userName = request.getParameter("userName").toString();
    			modelView.addObject("userName", userName);
			}
    		if (request.getParameter("status")!=null) {
    			status = request.getParameter("status").toString();
    			modelView.addObject("status", status);
			}
    		if (rangeDate!=null || startDate!=null || endDate!=null || StringUtils.isNotBlank(userName) || StringUtils.isNotBlank(status)) {
    			while (iterator.hasNext()) {
        			SimpleSession session = (SimpleSession)iterator.next();
        			Date lastLoginTime = session.getLastAccessTime();//最后登陆时间(记录时间为30分钟以内)
        			String sessionId = session.getId().toString();
        			User user = (User)session.getAttribute(RivuDataContext.USER_SESSION_NAME);
        			if(user==null){
        				continue;
        			}
    				Date date = user.getLoginTime();
    				//过滤条件成功标记 
    				boolean flag = false;
    				if (rangeDate!=null && startDate!=null && endDate!=null && StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(status)) {
    					if (date.after(rangeDate) && date.after(startDate) &&  date.before(endDate) && user.getUsername().contains(userName)) {
    						if (status.equals("0")) {
    							flag = true;
    						}else if(status.equals("1")){
    							if (lastLoginTime!=null) {
    								flag = true;
    							}else{
    								flag = false;
    								continue;
    							}
    						}else if(status.equals("2")){
    							if (lastLoginTime==null) {
    								flag = true;
    							}else{
    								flag = false;
    								continue;
    							}
    						}
    					}else{
							flag = false;
    						continue;
    					}
    				}else{
    					if (rangeDate!=null) {
    						if (date.after(rangeDate)) {
    							flag = true;
    						}else{
								flag = false;
    							continue;
    						}
    					}
    					if (startDate!=null) {
    						if (date.after(startDate)) {
    							flag = true;
    						}else{
								flag = false;
    							continue;
    						}
    					}
    					if (endDate!=null) {
    						if (date.before(endDate)) {
    							flag = true;
    						}else{
								flag = false;
    							continue;
    						}
    					}
    					if (StringUtils.isNotBlank(userName)) {
    						if (user.getUsername().contains(userName)) {
    							flag = true;
							}else{
								flag = false;
								continue;
							}
    					}
    					if (lastLoginTime!=null) {
    						if (status.equals("0")) {
    							flag = true;
    						}else if(status.equals("1")){
    							if (lastLoginTime!=null) {
    								flag = true;
    							}else{
    								flag = false;
    								continue;
    							}
    						}else if(status.equals("2")){
    							if (lastLoginTime==null) {
    								flag = true;
    							}else{
    								flag = false;
    								continue;
    							}
    						}
    					}
    				}
    				if (flag) {
    					//强制退出需要session id，故放置到该字段
    					user.setBirthday(sessionId);
    	    			compareList.add(user);
    				}
    			}
    			//处理分页
    			int beginNum = 1;
		    	if(request.getParameter("beginNum")!=null&&!"".equals(request.getParameter("beginNum"))){
		    		beginNum = Integer.valueOf(request.getParameter("beginNum"));
		    	}
		    	
				int endNum = 20;
				if(request.getParameter("endNum")!=null&&!"".equals(request.getParameter("endNum"))){
					endNum = Integer.valueOf(request.getParameter("endNum"));
				}
				int current = beginNum;
    			if (compareList!=null && compareList.size()>0) {
    				
    				int allrow = compareList.size();
    				
    				if(allrow>0){
    					int pageSize = endNum-beginNum;
    					String action = request.getParameter("action");
    					
    					if("first".equals(action)){
    						current=1;
    					}else if("last".equals(action)){
    						current=beginNum-1-pageSize>0?beginNum-pageSize-1:1;
    					}else if("next".equals(action)){
    						if(endNum+1<=allrow)
    						current=endNum+1;
    					}else if("final".equals(action)){
    						current=allrow-pageSize;
    					}
    					if(current<1)current=1;
    					for (int i = 0; i < compareList.size(); i++) {
							if(i>=current-1&&i<=current-1+pageSize){
								list.add(compareList.get(i));
							}
						}
    					endNum = current+pageSize;
    				}
    				
    				
    			}
    			modelView.addObject("beginNum",current);
				modelView.addObject("endNum",endNum);
    		}
    		
		}
    	modelView.addObject("onlineUserList",list);
    	modelView.addObject("data",data);
    	return modelView;
    }
    
    
    @RequestMapping(value="/removeonlineuser" , name="removeonlineuser" , type="manage",subtype="task")
    public ModelAndView removeonlineuser(HttpServletRequest request , @PathVariable String orgi , @Valid String[] userids, @ModelAttribute RequestData data) throws Exception{ 
    	ResponseData response = new ResponseData("redirect:/{orgi}/manage/task/onlineuser.html?msgcode=S_TASK_000001");
    	if(userids!=null&&userids.length>0){
    		for (String sessionid : userids) {
    	    	Collection<?> collections = RivuDataContext.getSessionDao().getActiveSessions();
    			Iterator iterator = collections.iterator() ;
    	    	while (iterator.hasNext()) {
    				SimpleSession session = (SimpleSession)iterator.next();
    				if (session.getId().equals(sessionid)) {
    					RivuDataContext.getSessionDao().delete(session);
    					break;
    				}
    	    	}
			}
    		
    	}
    
    	return this.onlineuser(request, orgi, data);
    }


    @SuppressWarnings("unchecked")
    @RequestMapping(value="/allplan" , name="allplan" , type="manage",subtype="task")
    public ModelAndView allplan(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/task/allplan") , orgi) ;
    	List<HistoryJobDetail> historytasks = null;
		historytasks = super.getService().findPageByCriteria(DetachedCriteria.forClass(HistoryJobDetail.class).add(Restrictions.eq("orgi",orgi)).addOrder(Order.desc("starttime")), data.getPs(), data.getP());
		DCriteriaPageSupport valueList = (DCriteriaPageSupport<?>)historytasks;
		data.setTotal(valueList.getTotalCount());
		data.setPages(valueList.getIndexes().length) ;
    	modelView.addObject("historytasks",historytasks);
    	modelView.addObject("data",data);
    	return modelView;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/allwarn" , name="allwarn" , type="manage",subtype="task")
    public ModelAndView allwarn(HttpServletRequest request , @PathVariable String orgi , @ModelAttribute RequestData data) throws Exception{ 
    	ModelAndView modelView = request(super.createManageTempletResponse("/pages/manage/task/allwarn") , orgi) ;
    	List<HistoryJobDetail> historytasks = null;
		historytasks = super.getService().findPageByCriteria(DetachedCriteria.forClass(HistoryJobDetail.class).add(Restrictions.eq("orgi",orgi)).addOrder(Order.desc("starttime")), data.getPs(), data.getP());
		DCriteriaPageSupport valueList = (DCriteriaPageSupport<?>)historytasks;
		data.setTotal(valueList.getTotalCount());
		data.setPages(valueList.getIndexes().length) ;
    	modelView.addObject("historytasks",historytasks);
    	modelView.addObject("data",data);
    	return modelView;
    }
    
    
    @SuppressWarnings("unchecked")
	@RequestMapping(value ="/searchsetting" , name ="searchsetting" , type ="manage", subtype ="task")
    public ModelAndView searchsetting(HttpServletRequest request , @PathVariable String orgi, @ModelAttribute RequestData data) throws Exception{
    	ModelAndView view = request(super.createManageTempletResponse("/pages/manage/task/searchsetting") , orgi) ;
    	List<SearchSetting> searchList = null;
    	searchList = super.getService().findPageByCriteria(DetachedCriteria.forClass(SearchSetting.class)
    			.add(Restrictions.eq("orgi", orgi)));
    	DCriteriaPageSupport valueList = (DCriteriaPageSupport<?>)searchList;
		data.setTotal(valueList.getTotalCount());
		data.setPages(valueList.getIndexes().length) ;
    	view.addObject("searchList",searchList);
    	view.addObject("data",data);
		return view; 
    }
    
	@RequestMapping(value ="/searchsettingadd/{name}/{service}" ,name ="searchsettingadd" ,type ="manage" , subtype = "task")
    public ModelAndView searchsettingadd(HttpServletRequest request , @PathVariable String orgi, @PathVariable String name, @PathVariable String service) throws Exception{
    	ResponseData responseData = new ResponseData("/pages/manage/task/searchsettingadd") ; 
    	List<SearchSetting> searchs = super.getService().findAllByCriteria(DetachedCriteria.forClass(SearchSetting.class)
    			.add(Restrictions.eq("orgi", orgi))
    			.add(Restrictions.eq("sitename", name)));
    	ModelAndView view = request(responseData , orgi);
    	if (searchs != null && searchs.size() >0){
    		view.addObject("search",searchs.get(0));
    	}else{
    		view.addObject("search",new SearchSetting());
    	}
    	//查询是否有设置邮件和短信
    	view.addObject(
				"site",
				super.getService().findAllByCriteria(
						DetachedCriteria.forClass(RivuSite.class).add(
								Restrictions.eq("orgi", orgi))));
    	//查询当前要设置预警的系统设置
		List<ConfigureParam> properties = super.getService().findAllByCriteria(DetachedCriteria.forClass(ConfigureParam.class)
													.add(Restrictions.eq("protype", service))
													.add(Restrictions.eq("name", name))
													.add(Restrictions.eq("orgi", orgi)));
		//查询到服务器列表
		DetachedCriteria criteria = DetachedCriteria.forClass(ClusterServer.class).add(Restrictions.eq("orgi",orgi));
    	view.addObject("clusterList", super.getService().findAllByCriteria(criteria)) ;
		
		if(properties != null && properties.size() >0){
			view.addObject("properties",properties.get(0));
		}else{
			view.addObject("properties",new ConfigureParam());
		}
		view.addObject("type",service);
		return view;
    }
    
	@RequestMapping(value ="/searchsettingaddo/{service}" ,name ="searchsettingaddo" ,type ="manage" , subtype = "task")
    public ModelAndView searchsettingaddo(HttpServletRequest request , @PathVariable String orgi,@Valid SearchSetting searchSetting,@PathVariable String service) throws Exception{
    	ResponseData response = new ResponseData(
				"redirect:/{orgi}/manage/system/{service}/servicesetting.html");
    	int count = super.getService().getCountByCriteria(
    			DetachedCriteria.forClass(SearchSetting.class)
    			.add(Restrictions.eq("orgi", orgi))
    			.add(Restrictions.eq("sitename", searchSetting.getSitename())));
    	if(count > 0){
    		//已经创建
    		List<SearchSetting> searchs = super.getService().findAllByCriteria(
        			DetachedCriteria.forClass(SearchSetting.class).add(Restrictions.eq("orgi", orgi))
        			.add(Restrictions.eq("sitename", searchSetting.getSitename())));
    		SearchSetting setting = new SearchSetting();
        	if (searchs != null && searchs.size() >0){
        		setting = searchs.get(0);
        		setting.setHlhtmlend(searchSetting.getHlhtmlend());
        		setting.setHlhtmlstart(searchSetting.getHlhtmlstart());
        		setting.setHlsnippets(searchSetting.getHlsnippets());
        		setting.setSitedesc(searchSetting.getSitedesc());
        		setting.setStartdelay(searchSetting.getStartdelay());
        		setting.setR3cloudserver(searchSetting.getR3cloudserver());
        		if(searchSetting.getSiteemail() == null){
        			setting.setSiteemail("msg");
        		}else{
        			setting.setSiteemail(searchSetting.getSiteemail());
        		}
        		setting.setSitename(searchSetting.getSitename());
        		setting.setSearchtype(searchSetting.getSearchtype());
        		super.getService().updateIObject(setting);
        	}
    		
    	}else{
    		if(searchSetting.getSiteemail() == null){
    			searchSetting.setSiteemail("msg");
    		}
    		searchSetting.setSpellcheck("1");
    		//保存预警信息
    		super.getService().saveIObject(searchSetting);
    	}
    	
    	return super.request(response, orgi);
    }
    
} 